from goods.models import GoodsChannel



def get_categories():
    """获取分类三级数据"""
    categories = {}   # 保存数据的字典
    # 获取一级所有数据
    goods_channels_qs = GoodsChannel.objects.order_by("group_id",'sequence')
    for channels in goods_channels_qs:
        group_id = channels.group_id    # 获取顶级数据的分组组号
        if group_id not in categories:   # 判断当前组号是否在字典中以存在
            # 诺不在，则创建键值对（以组号为键，在来个字典为值）
            categories[group_id] = {'channels': [], 'sub_cats': []}
        cat1 = channels.category  # 获取一级数据（以外建category获得）
        # 绑定一级数据的对应图片链接  （类似于创建类时，使用实例化对像去设置属性，而不是在init初始化中设置）
        cat1.url = channels.url
        categories[group_id]['channels'].append(cat1)   # 将获得的每个数据都添加到字典中

        cat2_qs = cat1.subs.all()   #  获取一级数据下的二级数据
        for cat2 in cat2_qs:   # 遍历
            cat3_qs = cat2.subs.all()  # 获取二级数据下的所有三级数据
            cat2.sub_cats = cat3_qs   #  将获得的三级数据绑定到二级数据的某个属性中去
            categories[group_id]['sub_cats'].append(cat2)   # 添加到字典中

    return categories


#  测试
# def text():
#     goods_qs = GoodsChannel.objects.all()
#     goods_dict = {}
#     for goods in goods_qs:
#         group_id = goods.group_id
#         if group_id not in goods_dict:
#             goods_dict[group_id] = {'channels': [], 'sub_cats': []}
#
#         cat1 = goods.category
#         goods_dict[group_id]['channels'].append(cat1)
#
#         cat2_qs = cat1.subs.all()
#         for cat2 in cat2_qs:
#             cat3_qs = cat2.subs.all()
#             cat2.goods = cat3_qs
#             goods_dict[group_id]['sub_cats'].append(cat2)